package com.example.openfeign;

import feign.Feign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cloud.openfeign.FeignFormatterRegistrar;
import org.springframework.context.annotation.Bean;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@AutoConfiguration
@ConditionalOnClass({Feign.class})
public class DefaultOpenfeignAutoConfiguration {
    private static final String DEFAULT_DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    private static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
    private static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";

    /**
     * 注册时间转换
     */
    @Bean
    public FeignFormatterRegistrar feignDateTimeFormatterRegistrar() {
        log.info("feignLocalDateTimeRegistrar autoconfig");
        return registry -> {
            registry.addConverter(LocalDateTime.class, String.class, source -> source.format(DateTimeFormatter.ofPattern(DEFAULT_DATETIME_PATTERN)));
            registry.addConverter(LocalDate.class, String.class, source -> source.format(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
            registry.addConverter(LocalTime.class, String.class, source -> source.format(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
            registry.addConverter(String.class, LocalDateTime.class, source -> LocalDateTime.parse(source, DateTimeFormatter.ofPattern(DEFAULT_DATETIME_PATTERN)));
            registry.addConverter(String.class, LocalDate.class, source -> LocalDate.parse(source, DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
            registry.addConverter(String.class, LocalTime.class, source -> LocalTime.parse(source, DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
        };
    }
}
